/**
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in
 * compliance with the License.You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied.  See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.pvacameras.server;

import com.google.pvacameras.server.config.Config;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Order Page Servlet that renders the order page and generates the MaskedWalletRequest.
 *
 *  Templating uses Velocity Template
 *
 *  The selections and information generated by the user are posted to the next page the confirm
 * servlet
 *
 *
 */
public class HomeServlet extends HttpServlet {
  /**
   * Get handler forwards request to post handler
   */
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    doPost(req, resp);
  }

  /**
   * Post handler renders the template generates the maskedWalletRequest and injects the JWT into
   * the template
   */
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    // So we don't write to velocity.log
    Velocity.setProperty(
        "runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute");

    // Initialize Velocity Templates
    try {
      Velocity.init();
    } catch (Exception e) {
      e.printStackTrace();
    }
    //TODO(user): Move stored info to browser cookies
    HttpSession session = req.getSession();
    String name = (String) session.getAttribute("name");
    String email = (String) session.getAttribute("email");
    String logoutFlag = req.getParameter("logout");

    if (req.getParameter("name") != null) {
      name = req.getParameter("name");
    }
    if (req.getParameter("email") != null) {
      email = req.getParameter("email");
    }

    VelocityContext context = new VelocityContext();

    context.put("walletJSUrl", Config.getEnvironment().isLocal() ? Config.getDevJsUrl(req)
        : Config.getEnvironment().getJsUrl());
    context.put("clientId", Config.OAUTH_CLIENT_ID);
    context.put("apiKey", Config.OAUTH_API_KEY);

    if (name != null && logoutFlag == null) {
      session.setAttribute("name", name);
      context.put("name", name);
    }

    if (email != null && logoutFlag == null) {
      session.setAttribute("email", email);
      context.put("email", email);
      context.put("truncEmail", email.substring(0, 6) + "...");
    }

    if (logoutFlag != null) {
      session.invalidate();
    }

    PrintWriter pw;

    try {
      // Get the response output stream PrintWriter
      pw = resp.getWriter();

      // Render the template and output to print stream
      Velocity.mergeTemplate("index.vm", "UTF-8", context, pw);
    } catch (ResourceNotFoundException e) {
      e.printStackTrace();
    } catch (ParseErrorException e) {
      e.printStackTrace();
    } catch (MethodInvocationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
